package com.demo.resourcecode.c10tx;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional(propagation = Propagation.REQUIRED)
public class UserServiceImpl2 {

	private JdbcTemplate jdbcTemplate;
	private PersonServiceImpl2 personService;

	// 设置数据源
	public void setDataSource(DataSource dataSource){
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public void setPersonService(PersonServiceImpl2 personService) {
		this.personService = personService;
	}

	public void save(Test t) throws Exception {
		jdbcTemplate.update("insert into test(id, name) values (?, ?)", new Object[]{t.getId(), t.getName()}, new int[]{java.sql.Types.INTEGER, java.sql.Types.VARCHAR});
		Test t2 = new Test();
		t2.setId(4);
		t2.setName("zsl4");
		try {
			personService.save(t2);
		}catch (RuntimeException e) {
			System.out.println("------------");
		}
		// 事务测试，加上这句则数据不会被保存到数据库中，注意默认情况下，spring中的事务处理只对RuntimeException方法进行回滚，如果换成Exception将不会回滚
		// throw new RuntimeException("aa");
	}

}
